//
//  Utils.m
//  ChinaBookingPhone
//
//  Created by 杨 锐 on 14-5-21.
//  Copyright (c) 2014年 xingheng. All rights reserved.
//

#import "UtilsHelper.h"
#import "CheckHelper.h"
#import "pinyin.h"

@implementation UtilsHelper

/**
 *  删除归档文件
 *
 *  @param filePath 文件路径
 */
+(void)deleArchiverFile:(NSString*)filePath{
    
    NSFileManager *defaultManager = [NSFileManager defaultManager];
    if ([defaultManager isDeletableFileAtPath:filePath]) {
        [defaultManager removeItemAtPath:filePath error:nil];
    }
}

/**
 *  MD5加密
 *
 *  @param input 需要加密字符串
 *
 *  @return 返回加密后字符串
 */
+(NSString*)MD5:(NSString *)input{
    
    const char *cStr = [input UTF8String];
    unsigned char digest[32];
    CC_MD5(cStr,(CC_LONG)strlen(cStr),digest); //This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return  output;
}

/**
 *  字符串EnCode
 *
 *  @param str 字符串
 *
 *  @return EnCode后的字符串
 */
+(NSString *)stringEnCode:(NSString *)str{
    
    return [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

/**
 *  字符串DeCode
 *
 *  @param str 字符串
 *
 *  @return DeCode后的字符串
 */
+(NSString *)stringDeCode:(NSString *)str{
    
    return [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

/**
 *  替换字符串特殊字符
 *
 *  @param content 需要替换的字符串
 *
 *  @return 返回替换后的字符串
 */
+(NSString*)stringReplace:(NSString*)content{
    
    content = [content stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    content = [content stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@" " withString:@""];
    content = [content stringByReplacingOccurrencesOfString:@"。" withString:@"."];
    content = [content stringByReplacingOccurrencesOfString:@"，" withString:@","];
    content = [content stringByReplacingOccurrencesOfString:@"、" withString:@","];
    content = [content stringByReplacingOccurrencesOfString:@"：" withString:@":"];
    content = [content stringByReplacingOccurrencesOfString:@"！" withString:@"!"];
    return content;
}

/**
 *  按指定长度截取字符串，超过指定长度显示省略号
 *
 *  @param string 要截取字符串
 *  @param count  截取长度
 *
 *  @return 返回截取字符串
 */
+(NSString *)stringAtIndexByCount:(NSString*)string withCount:(NSInteger)count{
    
    int i;
    int sum=0;
    for(i=0;i<[string length];i++)
    {
        unichar str = [string characterAtIndex:i];
        if(str < 256){
            sum+=1;
        }
        else {
            sum+=2;
        }
        if(sum>count){
            //当字符大于count时，剪取三个位置，显示省略号。否则正常显示
            NSString * str=[string substringWithRange:NSMakeRange(0,[self charAtIndexByCount:string withCount:count-2])];
            return [NSString stringWithFormat:@"%@...",str];
        }
    }
    return string;
}

/**
 *  转换string小写
 *
 *  @param string 传入字符串
 *
 *  @return 返回结果
 */
- (NSString *)lowercaseFirstCharacter:(NSString*)string {
    NSRange range = NSMakeRange(0,1);
    NSString *lowerFirstCharacter = [[string substringToIndex:1] lowercaseString];
    return [string stringByReplacingCharactersInRange:range withString:lowerFirstCharacter];
}

/**
 *  转换string大写
 *
 *  @param string 传入字符串
 *
 *  @return 返回结果
 */
- (NSString *)uppercaseFirstCharacter:(NSString*)string {
    NSRange range = NSMakeRange(0,1);
    NSString *upperFirstCharacter = [[string substringToIndex:1] uppercaseString];
    return [string stringByReplacingCharactersInRange:range withString:upperFirstCharacter];
}

/**
 *  数组顺序翻转
 *
 *  @param arr 数组
 *
 *  @return 返回倒序后数组
 */
+(NSArray *)ArrayOverTurn:(NSArray*)arr{
    
    NSMutableArray *ReslutArr = [[NSMutableArray alloc] init];
    for (int i = (int)arr.count-1; i>=0; i--)
    {
        [ReslutArr addObject:[arr objectAtIndex:i]];
    }
    return ReslutArr;
}

/**
 *  字符串按特殊字符分隔返回数组
 *
 *  @param split 特殊字符
 *  @param str   需要分割的字符串
 *
 *  @return 返回数组
 */
+(NSMutableArray *)returnStrArray:(NSString*)split str:(NSString *)str{
    
    if (str.length>0) {
        
        NSArray *temparray = [str componentsSeparatedByString:split];
        NSMutableArray *array = [[NSMutableArray alloc]init];
        //处理空字符串
        for (int i = 0; i < temparray.count; i++) {
            
            if (![CheckHelper checkEmptyString:[temparray objectAtIndex:i]]) {
                
                [array addObject:[temparray objectAtIndex:i]];
            }
        }
        return  array;
    }else{
        return  nil;
    }
}

/**
 *  按指定尺寸裁剪图片
 *
 *  @param image   原图
 *  @param newSize 裁切尺寸
 *
 *  @return 裁切后的图
 */
+(UIImage *)imageWithImageSize:(UIImage*)image scaledToSize:(CGSize)newSize{
    
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

/**
 *  等比裁剪图片
 *
 *  @param image  原图
 *  @param newSiz 裁切尺寸
 *
 *  @return 裁切后的图
 */
+(UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize{
    
    UIImage *img = image;
    int h = img.size.height;
    int w = img.size.width;
    
    if(h <= newSize.width && w <= newSize.height)
    {
        image = img;
    }
    else
    {
        float b = (float)newSize.width/w < (float)newSize.height/h ? (float)newSize.width/w : (float)newSize.height/h;
        CGSize itemSize = CGSizeMake(b*w, b*h);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0, 0, b*w, b*h);
        [img drawInRect:imageRect];
        img = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return img;
}

/**
 *  统计ASCII和Unicode混合文本长度的
 *
 *  @param text 需要统计的文本
 *
 *  @return 返回文本长度
 */
+(NSUInteger)unicodeLengthOfString:(NSString *)text{
    
    NSUInteger asciiLength = 0;
    
    for (NSUInteger i = 0; i < text.length; i++) {
        
        unichar uc = [text characterAtIndex: i];
        asciiLength += isascii(uc) ? 1 : 2;
    }
    
    NSUInteger unicodeLength = asciiLength / 2;
    if(asciiLength % 2) {
        unicodeLength++;
    }
    return unicodeLength;
}

/**
 *  获取一个随机数，范围在[from,to] 包括from 不包括to
 *
 *  @param from 包括from
 *  @param to   不包括to
 *
 *  @return 随机数
 */
+(NSInteger)getRandNum:(NSInteger)from to:(NSInteger)to{
    
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}

//超过count时，截取字符
+(NSInteger)charAtIndexByCount:(NSString*)string withCount:(NSInteger)count{
    
    int i;
    int sum=0;
    int count2=0;
    for(i=0;i<[string length];i++)
    {
        unichar str = [string characterAtIndex:i];
        if(str < 256){
            sum+=1;
        }
        else {
            sum+=2;
        }
        count2++;
        if (sum>=count){
            break;
        }
    }
    if(sum>count){
        return count2-1;
    }
    else{
        return count2;
    }
}

/**
 *  通过UIView获取当前UIViewController
 *
 *  @param sourceView 要查找的视图
 *
 *  @return 返回UIViewController
 */
+(UIViewController *)findViewController:(UIView *)sourceView{
    
    id target=sourceView;
    while (target) {
        target = ((UIResponder *)target).nextResponder;
        if ([target isKindOfClass:[UIViewController class]]) {
            break;
        }
    }
    return (UIViewController*)target;
}

/**
 *  根据拉伸图片生成按钮
 *
 *  @param NormalImg
 *  @param HighImg
 *  @param DisImg
 *  @param buttonFrame
 *
 *  @return 返回UIButton
 */
+(UIButton *)DrawStretchButtonWihtNormalImage:(UIImage*)NormalImg
                             HighlightedImage:(UIImage*)HighImg
                                     Disabled:(UIImage*)DisImg
                                  ButtonFrame:(CGRect)buttonFrame{
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:buttonFrame];
    UIEdgeInsets insets = UIEdgeInsetsMake(5,5,button.frame.size.height,button.frame.size.width);
    UIImage *stretchableImage = [NormalImg resizableImageWithCapInsets:insets];
    [button setBackgroundImage:stretchableImage forState:UIControlStateNormal];
    stretchableImage = [HighImg resizableImageWithCapInsets:insets];
    [button setBackgroundImage:stretchableImage forState:UIControlStateHighlighted];
    stretchableImage = [DisImg resizableImageWithCapInsets:insets];
    [button setBackgroundImage:stretchableImage forState:UIControlStateDisabled];
    return button;
}

/**
 *  计算中文首字母并返回该首字母char强转int后的索引值
 *
 *  @param  convertStr 需要转换的字符串
 *  @return 转换后char的int强转值
 */
+(NSInteger)ChineseStringFirstLetterConvert:(NSString *)convertStr
{
    if (convertStr.length > 0)
    {
        NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",
                                       pinyinFirstLetter([convertStr characterAtIndex:0])] uppercaseString];
        char bufchar = [singlePinyinLetter UTF8String][0];
        NSNumber *num = [NSNumber numberWithChar:bufchar];
        return [num integerValue];
    }
    else
    {
        NSNumber *num = [NSNumber numberWithChar:'#'];
        return [num integerValue];
    }
}

@end